<?php

class IndexController extends Controller{
    private $category;
	/**
	 * 判断网站状态（是否关闭）
	 * @return [type] [description]
	 */
	public function __init(){

		if (!C('WEBSTATUS')) {

			$this->display('web_close');

			exit;
		}
        $this->category=S('category');
        //分配品牌
        $this->assign('brand',S('brand'));
	}

    /**
     * 首页
     * @return [type] [description]
     */
    public function index(){
       
        $this->assign('category',Data::channelLevel($this->category));

        $this->display();
    }

    /**
     * 显示列表页
     * @return [type] [description]
     */
    public function category(){

    	$cid=Q('cid',0,'intval');

    	$data=M('category')->find($cid);

        // p($data);exit;

    	if(empty($data))$this->error('栏目不存在！',__ROOT__);

    	$this->assign('shop',$data);

        $this->assign('category',Data::channelLevel($this->category));

        //获取筛选属性
        $this->assign('attr',$this->getAttr());

        //获取商品列表
        $this->assignCategoryGoods();

    	$this->display('list.html');
    }

    /**
     * 显示详情页
     * @return [type] [description]
     */
    public function content(){

    	$gid = Q('gid',0,'intval');

    	$data=K('Goods')->find($gid);

        $cid=$data['category_cid'];

        $cate=Data::parentChannel($this->category,$cid);

        $this->assign('cate',$cate);

    	if(!$data)$this->error('商品不存在',__ROOT__);

        $goodsGallery=M('goods_gallery')->where("goods_gid=$gid")->all();

        $this->assign('goodsGallery',$goodsGallery);

    	$this->assign('goods',$data);

        $this->assign('attr',$this->getGoodsAttr($gid));

        $this->assign('category',Data::channelLevel($this->category));

    	$this->display();
    }
    /**
     * 品牌页
     * @return [type] [description]
     */
    public function brand(){
        $this->display();
    }
    
    /**
     * 获取商品属性
     * @param  [type] $gid [商品id]
     * @return [type]      [description]
     */
    public function getGoodsAttr($gid){

        $db=M('Goods');

        $sql="SELECT * FROM shop_attribute a JOIN shop_goods_attr ga ON a.attr_id=ga.attr_id WHERE ga.goods_gid=$gid GROUP BY a.attr_id  ORDER BY ga.attr_id ASC ";

        //获取属性值
        $attr=$db->query($sql);

        foreach ($attr as $id => $a) {
            
            $sql="SELECT * FROM shop_goods_attr WHERE attr_id={$a['attr_id']} AND goods_gid=$gid";

            $attr[$id]['attr']=$db->query($sql);
        }
        // p($attr);exit;
        return $attr;
    }
    /**
     * 详情页获取商品信息
     * @return [type] [description]
     */
    public function getProduct(){

        $id=Q('id',0,'trim');//异步发送的属性组合id
        // p($id);
        $map['goods_attr_id']=$id;//定义条件
        // p($map);exit;
        $data=M('product')->where($map)->find();//查询货品

        if ($data) {
            echo json_encode(array('status'=>1,'data'=>$data));exit;
        }else{
            echo json_encode(array('status'=>0,'msg'=> '货品不存在'));exit;
        }
    }

    /**
     * 获取商品并分配
     * @return [type] [description]
     */
    private function assignCategoryGoods(){

        $s=Q('s','','trim');

        $s=explode('-', $s);
        // p($s);
        $s=array_filter($s);
        // p($s);
        //栏目
        $cid=Q('cid',0,'intval');

        $cate[]=$cid;

        if (Data::hasChild($this->category,$cid)) {

            $cate[]=M('category')->where("pid=$cid")->getField('cid');

            if(Data::hasChild($this->category,$cate[1])){

                $cate[]=M('category')->where("pid=$cate[1]")->getField('cid');
            }
           
        }
        // p($cate);exit;
        // $cid=
        //没有筛选属性时
        //获取该栏目下所有商品
        if (empty($s)) {
            
            $db=M('goods');

            $map['category_cid']=array("IN",$cate);
            // p($map);
            $page=new Page($db->where($map)->count(),28);
            // p($db->where($map)->count());
            $data=$db->join("__goods__ g JOIN __brand__ b ON b.brand_id=g.brand_id")->where($map)->limit($page->limit())->all();
            // p($data);
        }else{

            //取属性对应id值
            $map['id']=array('IN',$s);
            // p($map);
            //取属性值字段
            $attr_value=M('goods_attr')->where($map)->getField('attr_value',true);
            // p($attr_value);
            $attr_value="'".implode("','", $attr_value)."'";

            $db = M();
            // p($attr_value);
            $sql="SELECT count(*) AS c FROM (select * from shop_goods_attr ga JOIN shop_goods g ON ga.goods_gid=g.gid WHERE ga.attr_value IN({$attr_value}) AND g.is_on_sale=1 GROUP BY ga.goods_gid HAVING count(*)=".count($s).') as good';

            $count=$db->query($sql);

            //避免$count没值时报错
            $count=empty($count)?0:$count;
            // p($count);
            $page=new Page($count[0]['c'],28);

            $sql="SELECT * FROM shop_goods_attr ga JOIN shop_goods g ON ga.goods_gid=g.gid JOIN shop_brand b ON g.brand_id=b.brand_id WHERE ga.attr_value IN({$attr_value}) GROUP BY ga.goods_gid HAVING count(*)=".count($s)." LIMIT ".$page->limit();
            
            $data=$db->query($sql);
            // p($db->getAllSql());
            // p($data);
        }

        $this->assign('data',$data);

        $this->assign('page',$page->show());
        
    }

    /**
     * 获取栏目属性
     * @return [type] [description]
     */
    private function getAttr(){

        //属性筛选的变量
        $s=Q('get.s',0,'trim');//此处不能用intval
        // p($s);
        //栏目cid
        $cid=Q('get.cid',0,'intval');

        if (!$cid) {
            $this->error('栏目不存在',__WEB__);exit;
        }
        // p($this->category);exit;
        //类型id
        $cat_id=$this->category[$cid]['cat_id'];
        // p($cat_id);
        if (!$s) {
            //$s没有值  组合出0-0-0方式
            $sql=" SELECT count(*) AS C FROM shop_attribute a JOIN shop_goods_attr ga ON a.attr_id=ga.attr_id WHERE a.cat_id=$cat_id GROUP BY a.attr_id";
            // p($sql);
            $count=count(M()->query($sql));
            // p($count);
            $s='';

            for ($i=0; $i <$count ; $i++) { 

                $s.='0-';

            }

            $s=substr($s, 0,-1);
            // p($s);
            go(U('category',array('cid'=>$cid,'s'=>$s)));

        }else{
            //当有$s值时
            $sql="SELECT * FROM shop_attribute a JOIN shop_goods_attr ga ON a.attr_id=ga.attr_id WHERE a.cat_id=$cat_id GROUP BY a.attr_id";
            // p($sql);
            //获取所有属性
            $attr=M()->query($sql);
            // p($attr);
            //取每一条属性的值
            foreach ($attr as $id => $v) {

                $sql="SELECT * FROM shop_goods_attr ga WHERE {$v['attr_id']}=ga.attr_id GROUP BY attr_value";

                $attr[$id]['_value']=M()->query($sql);
            }
            // p($attr);
            return $attr;
        }
    }

    /**
     * 异步筛选商品
     * @return [type] [description]
     */
    public function orderGoods(){

        $s=Q('s','','trim');

        $s=explode('-', $s);
        // p($s);
        $s=array_filter($s);
        // p($s);
        //栏目
        $cid=Q('cid',0,'intval');

        //没有筛选属性时
        //获取该栏目下所有商品
        if (empty($s)) {
            
            $db=M('goods');

            $map['category_cid']=array("IN",$cid);
            // p($map);
            $page=new Page($db->where($map)->count(),28);
            // p($db->where($map)->count());
            $data=$db->where($map)->limit($page->limit())->all();
            // p($data);
        }else{

            //取属性对应id值
            $map['id']=array('IN',$s);
            // p($map);
            //取属性值字段
            $attr_value=M('goods_attr')->where($map)->getField('attr_value',true);
            // p($attr_value);
            $attr_value="'".implode("','", $attr_value)."'";
            // p($attr_value);
            $sql="SELECT count(*) AS c FROM shop_goods_attr ga JOIN shop_goods g ON ga.goods_gid=g.gid WHERE ga.attr_value IN({$attr_value}) GROUP BY ga.goods_gid HAVING count(*)=".count($s);
            // p($sql);
            $count=M()->query($sql);
            // p($count);
            $page=new Page($count[0]['c'],28);

            $sql="SELECT * FROM shop_goods_attr ga JOIN shop_goods g ON ga.goods_gid=g.gid WHERE ga.attr_value IN({$attr_value}) GROUP BY ga.goods_gid HAVING count(*)=".count($s);

            $data=M()->query($sql);
            // p($data);
        }

        echo json_encode(array('data'=>$data ,'page' => $page->show()));
        exit;
    }
}
